﻿using FYSJcrm.Core.Common;
using FYSJcrm.Core.IRepository.PermManage;
using FYSJcrm.Core.Model.PermManage;
using FYSJcrm.Core.Web.Areas.PermManage.Models.AdminUserModels;
using FYSJcrm.Core.Web.Extensions.FilterExtensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace FYSJcrm.Core.Web.Areas.PermManage.Controllers
{
    [Area(nameof(PermManage))]
    public class AdminUserController : Controller
    {
        private readonly IManagerRepository _managerRepository;
        private readonly IManagerRoleRepository _managerRoleRepository;

        public AdminUserController(IManagerRepository managerRepository, IManagerRoleRepository managerRoleRepository)
        {
            _managerRepository = managerRepository;
            _managerRoleRepository = managerRoleRepository;
        }

        [CheckPermission("AdminList.Show")]
        public IActionResult List()
        {
            return View();
        }

        [CheckPermission("AdminList.Show")]
        public async Task<IActionResult> ListData(int page = 1, int limit = 10)
        {
            var managers = await _managerRepository.Select
                .LeftJoin(p => p.ManagerRole.Id == p.RoleId)
                .Count(out long total)
                .Page(page, limit)
                .ToListAsync<AdminUserViewModel>();

            return Json(new AjaxResult { Code = HttpCode.OK, Data = managers, TotalCount = total });
        }

        [CheckPermission("AdminList.Add")]
        public async Task<IActionResult> Add()
        {
            var managerRole = await _managerRoleRepository.Select.ToListAsync();

            return View(managerRole);
        }

        [HttpPost]
        [CheckPermission("AdminList.Add")]
        public async Task<IActionResult> Add(AdminUserAddModel model)
        {
            string salt = Utils.GetCheckCode(8);

            ManagerEntity manager = new ManagerEntity
            {
                RoleId = model.RoleId,
                UserName = model.UserName,
                Salt = salt,
                Password = DESEncrypt.Encrypt(model.Password, salt),
                RealName = model.RealName,
                TelPhone = model.TelPhone,
                IsLock = model.IsLock,
                Email = model.Email
            };

            manager = await _managerRepository.InsertAsync(manager);
            return manager.Id > 0 ? Json(new AjaxResult { Code = HttpCode.OK, Data = "添加管理员成功！" })
                : Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "添加管理员失败！" });
        }

        [CheckPermission("AdminList.Edit")]
        public async Task<IActionResult> Edit(int id)
        {
            AdminUserEditViewModel viewModel = new AdminUserEditViewModel
            {
                AdminUser = await _managerRepository.Select.Where(p => p.Id == id).FirstAsync(),
                Roles = await _managerRoleRepository.Select.ToListAsync()
            };

            return View(viewModel);
        }

        [HttpPost]
        [CheckPermission("AdminList.Edit")]
        public async Task<IActionResult> Edit(AdminUserEditModel model)
        {
            var manager = await _managerRepository.Select.Where(p => p.Id == model.Id).FirstAsync();

            if (manager == null)
            {
                return Json(new AjaxResult { Code = HttpCode.NotFound, ErrorMsg = "不存在该管理员" });
            }

            manager.Password = model.Password == "0|0|0|0" ? manager.Password : DESEncrypt.Encrypt(model.Password, manager.Salt);
            manager.RealName = model.RealName;
            manager.RoleId = model.RoleId;
            manager.TelPhone = model.TelPhone;
            manager.Email = model.Email;
            manager.IsLock = model.IsLock;

            await _managerRepository.UpdateAsync(manager);

            return Json(new AjaxResult { Code = HttpCode.OK, Data = "修改管理员成功！" });
        }

        [CheckPermission("AdminList.Edit")]
        public async Task<IActionResult> ChangePassword(int id)
        {
            var manager = await _managerRepository.Select.Where(p => p.Id == id).FirstAsync();
            return View(manager);
        }

        [HttpPost]
        [CheckPermission("AdminList.Edit")]
        public async Task<IActionResult> ChangePassword(AdminUserChangePasswordModel model)
        {
            var manager = await _managerRepository.Select.Where(p => p.Id == model.UserId).FirstAsync();

            if (manager == null)
            {
                return Json(new AjaxResult { Code = HttpCode.NotFound, ErrorMsg = "不存在该管理员" });
            }

            if (model.NewPassword != model.NewPassword2)
            {
                return Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "新密码与确认密码不一致！" });
            }

            if (DESEncrypt.Encrypt(model.OldPassword) != manager.Password)
            {
                return Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "旧密码输入错误！" });
            }

            manager.Password = DESEncrypt.Encrypt(model.NewPassword, manager.Salt);
            await _managerRepository.UpdateAsync(manager);

            return Json(new AjaxResult { Code = HttpCode.OK, Data = "修改密码成功！" });
        }

        [HttpPost]
        [CheckPermission("AdminList.Delete")]
        public async Task<IActionResult> Delete(int id)
        {
            int? userId = HttpContext.Session.GetInt32("LoginUserId");

            if (userId == id)
            {
                return Json(new AjaxResult { Code = HttpCode.Forbidden, ErrorMsg = "管理员不能删除自己！" });
            }

            var flag = await _managerRepository.DeleteAsync(p => p.Id == id);
            return flag > 0 ? Json(new AjaxResult { Code = HttpCode.OK, Data = "删除管理员成功！" })
                : Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "删除管理员失败！" });
        }

        [HttpPost]
        [CheckPermission("AdminList.Delete")]
        public async Task<IActionResult> BatchDelete(int[] selectedIds)
        {
            int? userId = HttpContext.Session.GetInt32("LoginUserId");

            List<int> list = new List<int>();

            if (selectedIds.Length > 0)
            {
                //循环出选中的Id中，是否有自身
                foreach (var id in selectedIds)
                {
                    if (id != userId)
                    {
                        list.Add(id);
                    }
                }
            }

            var count = await _managerRepository.DeleteAsync(p => list.Contains(p.Id));

            return count > 0 ? Json(new AjaxResult { Code = HttpCode.OK, Data = "成功删除" + count + "个管理员，删除失败" + (selectedIds.Length - count) + "个管理员" })
                    : Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "删除管理员失败！" });
        }
    }
}
